package com.kuiandjie.web;


import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Employee;
import com.kuiandjie.entity.Idea;
import com.kuiandjie.entity.Log;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.IdeaService;
import com.kuiandjie.service.LogService;
import com.kuiandjie.util.DateUtil;

public class EditIdeaServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		Project curp = (Project) session.getAttribute("curp");
		
		String id = request.getParameter("id");
		
		if(curp != null && id != null && !"".equals(id)) {
			String type = request.getMethod();
			int ideaId = Integer.parseInt(id);
			IdeaService is = new IdeaService();
			if("GET".equals(type)) {
				Idea idea = is.findIdeaById(ideaId);
				if(idea != null) {
					request.setAttribute("idea", idea);
					request.getRequestDispatcher("WEB-INF/views/editidea.jsp").forward(request, response);
				} else {
					response.sendRedirect("idea.jspx");
				}
			} else {
				String title = request.getParameter("title");
				String content = request.getParameter("content");
				Employee e = (Employee) session.getAttribute("employee");
				
				Idea i = new Idea();
				i.setContent(content);
				i.setTitle(title);
				i.setId(ideaId);
				is.updateIdea(i);
				
				Log log = new Log();
				log.setDesc("有了一个新想法<a href='idea.jspx?id=" + ideaId + "'>" + title + "</a>");
				log.setEmployeeId(e.getId());
				log.setProjectId(curp.getId());
				log.setTime(DateUtil.getNow());
				log.setName(e.getName());
				log.setPic(e.getPic());
				
				LogService ls = new LogService();
				ls.inserLog(log);
				
				request.setAttribute("msg", new Gson().toJson(log));
				request.getRequestDispatcher("msgflow.jspx").include(request, response);
				
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				out.print("10001");
				out.flush();
				out.close();
			}
		}
	}
}
